package com.github.caijh.mall.front.controller;

import java.util.ArrayList;
import java.util.List;

import com.github.caijh.commons.util.Strings;
import com.github.caijh.framework.web.controller.BaseController;
import com.github.caijh.mall.common.CommonResult;
import com.github.caijh.mall.common.PageParams;
import com.github.caijh.mall.marketing.response.StoreCouponFrontResponse;
import com.github.caijh.mall.marketing.response.StoreCouponUserOrder;
import com.github.caijh.mall.marketing.service.StoreCouponService;
import com.github.caijh.mall.marketing.service.StoreCouponUserService;
import com.github.caijh.mall.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController("CouponFrontController")
@RequestMapping("api/front")
@Api(tags = "优惠券")
public class CouponController extends BaseController {

    @Autowired
    private StoreCouponService storeCouponService;

    @Autowired
    private StoreCouponUserService storeCouponUserService;

    @Autowired
    private UserService userService;


    /**
     * 分页显示优惠券表
     *
     * @param type       类型，搜索产品指定优惠券
     * @param productId  产品id，搜索产品指定优惠券
     * @param pageParams 分页参数
     */
    @ApiOperation(value = "分页列表")
    @GetMapping(value = "/coupons")
    public CommonResult<List<StoreCouponFrontResponse>> getList(
            @RequestParam(value = "type", defaultValue = "0") int type,
            @RequestParam(value = "productId", defaultValue = "0") int productId,
            @Validated PageParams pageParams) {

        if (type == 0) {
            productId = 0;
        }

        return CommonResult.success(storeCouponService.getListByUser(productId, pageParams, userService.getCurrentUserId()));
    }

    /**
     * 根据购物车id获取可用优惠券
     *
     * @param cartId 购物车id
     * @return 优惠券集合
     */
    @ApiOperation(value = "当前购物车可用优惠券")
    @RequestMapping(value = "coupons/order", method = RequestMethod.GET)
    public CommonResult<List<StoreCouponUserOrder>> getCouponsListByCartId(@RequestParam String cartId) {
        try {
            Strings.toIntListByComma(cartId);
        } catch (NumberFormatException e) {
            return CommonResult.success(new ArrayList<StoreCouponUserOrder>());
        }
        return CommonResult.success(storeCouponUserService.getListByCartIds(Strings.toIntListByComma(cartId)));
    }

}



